/// <reference path="jquery.d.ts" />
/// <reference path="extensions.ts" />

module App {
    export function init(options: IOptions) {
        var data = <IData>$(document.body).data("App");
        if (typeof data == "undefined") {
            $.extend(data, options);

            $("[data-role='view']:gt(0)").hide();

            $(document.body).data("App", {
                currentView: $("[data-role='view']").eq(0)
            });

            $(document.body).on("click", "a", function (event) {
                App.navigate((<HTMLAnchorElement>this).href);
                event.preventDefault();
            });

            //handle back and foward

            $(App).trigger("ready");
        }

    }

    export function navigate(url: string) {
        var data = <IData>$(document.body).data("App");
        console.log(url);
        if (url[0] == '#') {
            console.log("CALLED");
        } else {
            //TODO: Generate ID
            $.ajax(url, {
                type: 'POST',
                async: false,
                data: {},
                success: function (result) {
                    var $view = $(result.html);
                    addView($view, function () {
                        data.currentView.hide();
                        $view.show();
                        data.currentView = $view;
                    });
                }
            });
        }
    }

    function addView($view: JQuery, callback: () => void) {
        $(document.body).append($view);
        //init controls here
        callback();
    }

    export function onReady(callback: () => void ) {
        $(App).bind("ready", callback);
    }

    interface IData {
        baseURL: string;
        viewPath: string;
        currentView: JQuery;
    }

    export interface IOptions {
        baseURL: string;
        viewPath: string;
    }
}
